"""
杂交算子
"""
from random import choices
import numpy as np


def crossover(pops, mutantPops, Cr):
    """
    Params:
        :param pops: 第一次为初始化的种群，之后为select1选择后的种群
        :param mutantPops:经过突变后形成的种群
        :param Cr:交叉概率 0.9
        :return:
    """
    nPop, nChr = pops.shape
    choiMuPops1 = np.random.rand(nPop, nChr) < Cr  # 选择变异向量的位置1 
    choiMuPops2 = np.random.randint(0, nPop, (nPop, nChr)) == np.tile(np.arange(nChr), (nPop, 1))  # 选择变异向量的位置2
    choiMuPops = choiMuPops1 | choiMuPops2
    choiPops = ~ choiMuPops
    # choiMuPops中True占的比例比较大
    trialPops = mutantPops * choiMuPops + pops * choiPops
    return trialPops


if __name__ == "__main__":
    temp1 = np.random.randint(0, 4, (4, 2))
    # np.tile 把数组沿各个方向复制
    temp2 = np.tile(np.arange(2), (4, 1))
    choiMuPops2 = (temp1 == temp2)
    # temp1 [[0 1]
    #  [2 0]
    #  [0 2]
    #  [0 1]]
    print("temp1", temp1)
    # temp2 [[0 1]
    #  [0 1]
    #  [0 1]
    #  [0 1]]
    print("temp2", temp2)
    # choiMuPops2 [[ True  True]
    #  [False False]
    #  [ True False]
    #  [ True  True]]
    print("choiMuPops2", choiMuPops2)

    print("---------------------")
    # [[0 1 0 1]
    #  [0 1 0 1]
    #  [0 1 0 1]]
    print(np.tile(np.arange(2), (3, 2)))

    print("---------------------")
    mutantPops = np.array([[1, 2, 3], [4, 5, 6]])
    choiMuPops = np.array([[True, True, False], [False, True, True]])
    trialPops = mutantPops * choiMuPops
    # [[1 2 0]
    #  [0 5 6]]
    print(trialPops)
